package cc.wfu.trigger.job;

import cc.wfu.domain.order.event.OrderMessageEvent;
import cc.wfu.domain.order.service.IProductOrder;
import cc.wfu.infrastructure.event.EventPublisher;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @description 订单补货任务
 */
@Slf4j
@Component
public class OrderReplenishmentJob {

    @Resource
    private IProductOrder orderService;

    @Resource
    private EventPublisher eventPublisher;

    @Resource
    private OrderMessageEvent orderMessageEvent;

    /**
     * 每隔5分钟执行一次该方法
     * 执行订单补货，超时3分钟，已支付，待发货未发货的订单
     */
    @Scheduled(cron = "0 0/5 * * * ?")
    public void exec() {
        try {
            // 查询待补货订单
            List<String> orderIds = orderService.queryReplenishmentOrder();
            if (orderIds == null || orderIds.isEmpty()) {
                log.info("定时任务，订单补货不存在，查询 orderIds is empty");
                return;
            }
            for (String orderId : orderIds) {
                log.info("定时任务，订单补货开始。orderId: {}", orderId);
                // 发布消息, 进行发货处理
                eventPublisher.publish(orderMessageEvent.topic(), orderMessageEvent.buildEventMessage(orderId));
                log.info("定时任务，订单补货成功。orderId: {}", orderId);
            }
        } catch (Exception e) {
            log.error("定时任务，订单补货失败。", e);
        }
    }

}
